

import javax.telephony.Terminal;
import javax.telephony.TerminalConnection;
import javax.telephony.Call;
import javax.telephony.Connection;
import javax.telephony.events.CallEv;
import javax.telephony.events.TermConnRingingEv;
import javax.telephony.events.TermConnEv;
import javax.telephony.events.TermConnDroppedEv;

import javax.telephony.media.MediaTerminalConnection;
import javax.telephony.media.MediaCallObserver;
import javax.telephony.media.events.MediaTermConnAvailableEv;
import javax.telephony.media.events.MediaTermConnStateEv;
import javax.telephony.media.events.MediaTermConnDtmfEv;
import javax.telephony.media.events.MediaTermConnUnavailableEv;

import java.net.URL;
import java.io.File;
import java.io.FileWriter;
import java.sql.SQLException;

import gdbpack.Database;
import ttspack.TextToSpeech;
import mailpack.MailAccess;

public class EventsHandler extends java.lang.Object implements
		MediaCallObserver {
	int j = 0, totalMessages = 0;
	int dtmf = 0;
	char digits[] = new char[5];
	int password;
	int mailCount = 1;
	int validPassword = 0;
	String addr, epass;
	int count = 0;

	// Call object represents the telephone call

	private Call m_call = null;

	// m_TerminalConnection & m_destTerminalConnection represents
	// remote & this terminal respectively

	private TerminalConnection m_terminalConnection = null;
	private TerminalConnection m_destTerminalConnection = null;
	private boolean bOrig = false;
	// m_connections is the array of connections

	private Connection m_connections[] = null;

	// Class which do text to speech
	TextToSpeech t1 = new TextToSpeech();

	// Class which handle all database
	Database db1 = new Database();

	// Class to access mails
	MailAccess m1 = new MailAccess();

	/*
	 * Method callChangedEvent reports all events associated with the Call
	 * object. This method passes an array of CallEv objects as its arguments
	 * which correspond to the list of events representing the changes to the
	 * Call object as well as changes to all of the Connection and
	 * TerminalConnection objects associated with this Call.
	 */

	public void callChangedEvent(CallEv evlist[]) {

		if (m_call == null) {
			// setMVars function adds callObserver to the terminal
			bOrig = false;
			setMVars(evlist[0].getCall());
		}
		for (int i = 0; i < evlist.length; i++) {

			CallEv ev = evlist[i];

			// if the event is Ringing event
			switch (ev.getID()) {
			case TermConnRingingEv.ID: {
				TerminalConnection tc = ((TermConnEv) ev)
						.getTerminalConnection();
				try {
					// Establishes the Call
					tc.answer();

					System.out.println("Call Established");
				} catch (Exception excp) {
					System.out.println("Can not establish call"
							+ excp.toString());
					// Disconnect the connection
				}
				break;
			}
			case MediaTermConnAvailableEv.ID: {

				/*
				 * The MediaTermConnAvailableEv interface indicates that media
				 * is currently available on the TerminalConnection. Media
				 * becomes available on the TerminalConnection when the state of
				 * the TerminalConnection changes with respect to the telephone
				 * call.
				 */

				try {
					TerminalConnection tc = ((TermConnEv) ev)
							.getTerminalConnection();
					MediaTerminalConnection mtc = (MediaTerminalConnection) tc;
					mtc.setDtmfDetection(true);
					Messages("Welcome to phonomail system.\n"
							+ "Press 1 to read the mail\n"
							+ "Press 2 to skip the mail\n"
							+ "Press 3 to cancel reading current mail\n"
							+ "Now please enter your phonomail password", mtc);
				} catch (Exception excp) {
					TerminalConnection tc = ((TermConnEv) ev)
							.getTerminalConnection();
					MediaTerminalConnection mtc = (MediaTerminalConnection) tc;
					ErrorMsg(
							"Error in getting media connection. Please try afterwords",
							mtc);
					hangup(mtc);
				}
				break;
			}
			case MediaTermConnUnavailableEv.ID: {

				/*
				 * The MediaTermConnUnavailableEv interface indicates that there
				 * is currently no media available on the TerminalConnection.
				 * This event is most likely cause by a change in state of the
				 * TerminalConnection which respect to the call. For example,
				 * when someone goes on hold, media is no longer avaiable on
				 * that TerminalConnection
				 */
				if (ev instanceof MediaTermConnUnavailableEv) {
					try {
						TerminalConnection tc = ((TermConnEv) ev)
								.getTerminalConnection();
						MediaTerminalConnection mtc = (MediaTerminalConnection) tc;
						mtc.setDtmfDetection(false);
						hangup(mtc);
					} catch (Exception excp) {
						TerminalConnection tc = ((TermConnEv) ev)
								.getTerminalConnection();
						MediaTerminalConnection mtc = (MediaTerminalConnection) tc;
						ErrorMsg(
								"Media connection is currently unavailable.Please try afterwords",
								mtc);
						hangup(mtc);
					}
				}
				break;
			}

			case MediaTermConnDtmfEv.ID: {

				/*
				 * The MediaTermConnDtmfEv interface indicates that a DTMF-tone
				 * has been detection on the telephone line
				 */
				TerminalConnection tc = ((TermConnEv) ev)
						.getTerminalConnection();
				MediaTerminalConnection mtc = (MediaTerminalConnection) tc;

				if (validPassword == 1) // Entered full password
				{
					try {
						char yesno = ((MediaTermConnDtmfEv) ev).getDtmfDigit();

						switch (yesno) {
						case '1': // Read mail
							get_mails(mtc, 1);
							System.out.println("Read Mail :" + mailCount);
							get_mails(mtc, 0);
							break;

						case '2': // Skip mail
							mailCount++;
							get_mails(mtc, 0);
							break;

						case '3': // cancel reading
							mtc.stopPlaying();
							mailCount++;
							get_mails(mtc, 0);
							break;

						default:

						}
					} catch (Exception excp) {
						ErrorMsg(
								"Sorry, We can not accept your choice.Please try afterwords",
								mtc);
						hangup(mtc);
					}

				} else {
					// Array to hold PhonoMail Password
					digits[dtmf] = ((MediaTermConnDtmfEv) ev).getDtmfDigit();
					dtmf++;
					if (dtmf == 5) {
						String pass1 = new String(digits);
						Integer temp;
						password = Integer.parseInt(pass1);
						try {
							db1.getDatabaseConnection();

							// Get uesr's Email-ID & Email Password
							db1.returnMailInfo(password);
							addr = db1.emailId;
							epass = db1.emailPass;
							System.out.println(addr);
							System.out.println(epass);
							db1.closeDataBaseConnection();
							validPassword = 1;

							// Connect to mail server & get
							// Total Messages
							totalMessages = m1.getConnection("172.16.0.17",
									addr, epass);
							System.out.println(totalMessages);
							get_mails(mtc, 0);
						} catch (SQLException e) {
							Messages(
									"You have entered wrong password.Please enter correct password",
									mtc);
							validPassword = 0;
							dtmf = 0;

						} catch (Exception excp) {
							ErrorMsg(
									"Your mail account can not be accessed.Please try afterwords",
									mtc);
							hangup(mtc);
						}
					}

				}
				break;
			}

			default:
				// System.out.println ( "\n"+ev.toString ( ) ) ;

			}
		}
	}

	/*
	 * Function to access mails in text form,convert it into Audio files and
	 * playing that file on teletphone line
	 */

	public void get_mails ( MediaTerminalConnection mtc,int flag )  
   {  
    try 
     {  
      if ( mailCount < =totalMessages )  
       {  
        int state; 
        if ( flag==0 )     // read only subject of mail
         {  
          System.out.println ( "Header Mailcount : "+mailCount ) ; 
          m1.getMessage ( mailCount ) ; 
          t1.tts ( "Header.txt" ) ; 
         
          do 
           {  
            state = mtc.getMediaState (  ) ; 
                    state = state & MediaTerminalConnection.PLAYING; 
           } while ( state!=0 ) ; 
           
          mtc.usePlayURL ( new URL ( "file:C:\\PhonoMail\\ULaw\\Mail.wav" )  ) ; 
              mtc.startPlaying (  ) ;  
             }  
            if ( flag==1 )     // read body part also
             {  
              System.out.println ( "Body Mailcount : "+mailCount ) ; 
              t1.tts ( "Mail.txt" ) ; 
              do 
           {  
            state = mtc.getMediaState (  ) ; 
                    state = state & MediaTerminalConnection.PLAYING; 
           } while ( state!=0 ) ; 
           
          mtc.usePlayURL ( new URL ( "file:C:\\PhonoMail\\ULaw\\Mail.wav" )  ) ; 
          mtc.startPlaying (  ) ;  
          mailCount++; 
             }  
           }  
          else 
           {  
            ErrorMsg ( "You don't have further mails. Good Bye.",mtc ) ; 
            hangup ( mtc ) ; 
           }  
       }  
    catch  ( Exception excp )   
     {  
        ErrorMsg ( "System is not working properly. Please try afterwords",mtc ) ; 
        hangup ( mtc ) ; 
       }  
   }	// Fuction to play Error messages

	public void ErrorMsg(String msg, MediaTerminalConnection mtc) {
		try {
			FileWriter ErrMsg = new FileWriter("Error.txt");
			ErrMsg.write(msg);
			ErrMsg.close();
			t1.tts("Error.txt");
			mtc.usePlayURL(new URL("file:C:\\PhonoMail\\ULaw\\Mail.wav"));
			mtc.startPlaying();
			int state;
			do {
				state = mtc.getMediaState();
				state = state & MediaTerminalConnection.PLAYING;
			} while (state != 0);
			hangup(mtc);
		} catch (Exception e) {
			System.out.println(e);
			hangup(mtc);
		}
	}

	// Fuction to play simple messages
	public void Messages(String msg, MediaTerminalConnection mtc) {
		try {
			FileWriter Msg = new FileWriter("Messages.txt");
			Msg.write(msg);
			Msg.close();
			t1.tts("Messages.txt");
			mtc.usePlayURL(new URL("file:C:\\PhonoMail\\ULaw\\Mail.wav"));
			mtc.startPlaying();
		} catch (Exception e) {
			System.out.println(e);
			hangup(mtc);
		}
	}

	// Function to add callObserver to the terminal
	private void setMVars(Call c) {
		m_call = c;
		try {

			m_connections = c.getConnections();
			TerminalConnection[] tc;
			if (bOrig == false) {
				m_call.addObserver(this);
				tc = m_connections[0].getTerminalConnections();
				m_terminalConnection = tc[0];
				Terminal t = m_terminalConnection.getTerminal();
				t.addCallObserver(this);
			}
			tc = m_connections[1].getTerminalConnections();
			m_destTerminalConnection = tc[0];

		} catch (Exception e) {
			System.out.println(e);
		}
	}

	// Function to Disconnect the call & Reinitialising Variables
	public void hangup(MediaTerminalConnection mtc) {

		try {
			mtc.getConnection().disconnect();

			m_call = null;
			m_connections = null;
			m_terminalConnection = null;
			m_destTerminalConnection = null;
		} catch (Exception excp) {
			System.out.println("APPLICATION IS NOT FUNCTIONING PROPERLY "
					+ "MANUALLY RESTART THE APPLICATION\n");
			System.out.println(excp);
		} finally {
			j = 0;
			totalMessages = 0;
			dtmf = 0;
			mailCount = 1;
			validPassword = 0;
			addr = "";
			epass = "";
			password = 0;

		}

	}
}